using System;
using System.Collections.Generic;
using System.Net.Sockets;
using Dto;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
using Util;

namespace Net
{
    public class ClientPeer
    {
        private Socket _socket;
        private string _ip;
        private int _port;



        /**
         * 构造连接对象
         */
        public ClientPeer(string ip, int port)
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            this._ip = ip;
            this._port = port;
        }

        public void Connect()
        {
            try
            {
                _socket.Connect(_ip, _port);
                Debug.Log("连接服务器成功!");
                startReceive();
            }
            catch (Exception e)
            {
                Debug.Log(e.Message);
                throw;
            }
        }

        #region 接受数据
        /**
         * 接受的数据缓冲区
         */
        private byte[] _receiveBuffer = new byte[1024];
        /**
         * 接收到数据 存到缓冲区里
         */
        private List<byte> _dataCache = new List<byte>();

        private bool _isProcessReceive = false;

        public Queue<ResBase> SocketMsgQueue = new Queue<ResBase>();
        /**
         * 开始异步接受数据
         */
        private void startReceive()
        {
            if (_socket == null && _socket.Connected == false)
            {
                Debug.LogError("没有连接成功,无法发送数据");
                return;
            }

            _socket.BeginReceive(_receiveBuffer,0,1024,SocketFlags.None,receiveCallBack,_socket);
        }
    
        /**
         * 收到消息的回调
         */
        private void receiveCallBack(IAsyncResult ar)
        {
            try
            {
                int length = _socket.EndReceive(ar);
                byte[] tmpByteArray = new Byte[length];
                Buffer.BlockCopy(_receiveBuffer,0,tmpByteArray,0,length);
                // 处理收到的消息
                _dataCache.AddRange(tmpByteArray);
                if (_isProcessReceive == false)
                {
                    processReceive();
                }
                startReceive();
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
            
        }
        
        /**
         * 处理收到的数据
         */
        private void processReceive()
        {
            _isProcessReceive = true;
            
            // byte[] data = EncodeTool.DecodePacket(ref _dataCache);

            byte[] data=_dataCache.ToArray();

            if (data == null || data.Length == 0)
            {
                _isProcessReceive = false;
                return;
            }
            string jsonstr = System.Text.Encoding.UTF8.GetString(data);
            Debug.Log("客户端接受响应"+jsonstr);
            ResBase msg =JsonConvert.DeserializeObject<ResBase>(jsonstr);
            // 存储消息等待处理
            SocketMsgQueue.Enqueue(msg);
            _dataCache.Clear();
            processReceive();
            
        }
        #endregion

 

        #region 发送数据

        public void Send(int code, int subCode,object message)
        {
            ReqBase reqBase = new ReqBase(code,subCode,message);
            Send(reqBase);
        }

        public void Send( ReqBase reqBase)
        {
            string json =JsonConvert.SerializeObject(reqBase);
            Debug.Log("客户端发送请求:"+json);
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes ( json );
            /*byte[] data = EncodeTool.EncodeMsg(reqBase);
            byte[] packet = EncodeTool.EncodePacket(data);*/

            try
            {
                _socket.Send(byteArray);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }

        #endregion
    }
}